/**
 * Copyright © 2018 organization 苞米豆
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.baomidou.dynamic.datasource;

import com.baomidou.dynamic.datasource.util.DynamicDataSourceContextHolder;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * The core DynamicRoutingDataSource,It use determineCurrentLookupKey to determineDatasource.
 *
 * @author TaoYu Kanyuxia
 * @since 1.0.0
 */
@Slf4j
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {

    private static final String MASTER = "master";
    private static final String SLAVE = "slave";


    private Map<String, DataSource> dataSourceMap;

    private List<String> masterDataSources = new ArrayList<>();

    private List<String> slaveDataSources = new ArrayList<>();

    private DataSource defaultDataSource;

    private boolean master_slave_mode = false;

    @Setter
    private DynamicDataSourceProvider dynamicDataSourceProvider;
    @Setter
    private DynamicDataSourceStrategy dynamicDataSourceStrategy;

    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceContextHolder.getDataSourceLookupKey();
    }

    @Override
    protected DataSource determineTargetDataSource() {
        if (master_slave_mode) {

        } else {

        }
        return dataSourceMap.get(determineCurrentLookupKey());
    }

    @Override
    public void afterPropertiesSet() {
        this.dataSourceMap = dynamicDataSourceProvider.loadDataSource();
        for (Map.Entry<String, DataSource> entry : dataSourceMap.entrySet()) {
            String dsName = entry.getKey();
            if (dsName.contains("_")) {
                String[] groupMode = dsName.split("_");
                String mode = groupMode[1];
                if (MASTER.equals(mode)) {
                    masterDataSources.add(dsName);
                } else if (SLAVE.equals(mode)) {
                    slaveDataSources.add(dsName);
                }
            }
        }
        if (!masterDataSources.isEmpty()) {
            this.master_slave_mode = true;
        }

    }

}